// Copyright (c) 2020-present, INSPUR Co, Ltd. All rights reserved.
// This source code is licensed under Apache 2.0 License.
//
// Created by florian on 05.08.15.

#include "pure_mem/epoche.h"
#include "tree_node.h"
#include <algorithm>
#include <assert.h>
#include <emmintrin.h> // x86 SSE intrinsics

namespace syn_art_fullkey {

void N::writeLockOrRestart(bool &needRestart) {
  uint64_t version;
  do {
    version = typeVersionLockObsolete_.load();
    while (isLocked()) {
      _mm_pause();
      version = typeVersionLockObsolete_.load();
    }
    if (isObsolete()) {
      needRestart = true;
      return;
    }
  } while (
      !typeVersionLockObsolete_.compare_exchange_weak(version, version + 0b10));
}

void N::insertAndUnlock(N *node, N *parentNode, uint8_t keyParent, uint8_t key,
                        N *val, bool &needRestart) {
  N::insertGrow(node, parentNode, keyParent, key, val, needRestart);
  node->writeUnlock();
}

} // namespace syn_art_fullkey
